package com.zjsru.oneDay202210;

/**
 * @Author: CookLee
 * @Date: 2022/10/23
 * 交替合并字符串
 * 给你两个字符串 word1 和 word2 。请你从 word1 开始，通过交替添加字母来合并字符串。如果一个字符串比另一个字符串长，就将多出来的字母追加到合并后字符串的末尾。
 *
 * 输入：word1 = "abc", word2 = "pqr"
 * 输出："apbqcr"
 * 解释：字符串合并情况如下所示：
 * word1：  a   b   c
 * word2：    p   q   r
 * 合并后：  a p b q c r
 *
 * 输入：word1 = "ab", word2 = "pqrs"
 * 输出："apbqrs"
 * 解释：注意，word2 比 word1 长，"rs" 需要追加到合并后字符串的末尾。
 * word1：  a   b
 * word2：    p   q   r   s
 * 合并后：  a p b q   r   s
 */
public class MergeAlternately {
    
    /**
     * 模拟出所有的可能性，即三种情况： 长度不一致2这种和长度一致
     *
     * */
    public String mergeAlternately(String word1, String word2) {
        StringBuilder sb = new StringBuilder();
        char[] chars1 = word1.toCharArray();
        char[] chars2 = word2.toCharArray();
        if (chars1.length < chars2.length) {
            for (int i = 0, j = 0; j < chars2.length; j++) {
                if (i < chars1.length) {
                    sb.append(chars1[i]);
                }
                sb.append(chars2[j]);
                i++;
            }
        } else if (chars1.length > chars2.length) {
            for (int i = 0, j = 0; i < chars1.length; i++) {
                sb.append(chars1[i]);
                if (j < chars2.length) {
                    sb.append(chars2[j]);
                }
                j++;
            }
        } else {
            for (int i = 0, j = 0; i < chars1.length; i++) {
                sb.append(chars1[i]);
                sb.append(chars2[j]);
                j++;
            }
        }
        return sb.toString();
    }
    
    /**
     * 另一种模拟方式， 更加简单
     * */
    public String mergeAlternately2(String s1, String s2) {
        int n = s1.length(), m = s2.length(), i = 0, j = 0;
        StringBuilder sb = new StringBuilder();
        while (i < n || j < m) {
            if (i < n) {
                sb.append(s1.charAt(i++));
            }
            if (j < m) {
                sb.append(s2.charAt(j++));
            }
        }
        return sb.toString();
    }
    
    public static void main(String[] args) {
        MergeAlternately mergeAlternately = new MergeAlternately();
        String word1 = "abcd";
        String word2 = "pq";
        System.out.println(mergeAlternately.mergeAlternately2(word1, word2));
    }
}
